package com.util.map;

import org.junit.Test;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * @Description
 * @Author away
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/3/13
 */
public class WeakHashMapDemo {

    /**
     * 每次 GC 时回收 map里面保存的对象，但是发现只有 Full GC 时才把map中的回收完，否则都会剩下一个，
     * -Xms20m -Xmx20m -verbose:gc
     */
    @Test
    public void test() {
        Map<String, byte[]> caches = new WeakHashMap<>();
        for (int i = 0; i < 100000; i++) {
            caches.put(i + "", new byte[1024 * 1024 * 1]);
            System.out.println("put num: " + i + " but caches size:" + caches.size());
        }
    }
    /* output test
[GC (Allocation Failure)  13414K->12320K(18944K), 0.0024986 secs]
[Full GC (Ergonomics)  12320K->5120K(18944K), 0.0170718 secs]
put num: 1185 but caches size:1
put num: 1186 but caches size:2
put num: 1187 but caches size:3
[GC (Allocation Failure)  8262K->8256K(18944K), 0.0011849 secs]
put num: 1188 but caches size:2
put num: 1189 but caches size:3
put num: 1190 but caches size:4
[GC (Allocation Failure)  11398K->10272K(18944K), 0.0021005 secs]
put num: 1191 but caches size:2
put num: 1192 but caches size:3
put num: 1193 but caches size:4
     */
}
